package org.istt.web;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailService {

	private JavaMailSender mailSender;
	
	private String sender;
	
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
 
	public void sendMail(String from, String to, String subject, String msg, String attachFile) throws Exception{
 
		MimeMessage message = mailSender.createMimeMessage();
		   try{
				MimeMessageHelper helper = new MimeMessageHelper(message, true);
		 
				helper.setFrom(from);
				helper.setTo(to);
				helper.setText(msg);
				if(StringUtils.isEmpty(subject)) subject = "Thong bao";
					helper.setSubject(subject);
	
				FileSystemResource file = new FileSystemResource(attachFile);
				helper.addAttachment(file.getFilename(), file);
		 
				mailSender.send(message);	
		     }catch (MessagingException e) {
		    	 throw new MailParseException(e);
		     }catch (Exception e) {
				// TODO: handle exception
		    	 throw new Exception(e);
			}
	}

	public void setSender(String sender) {
		this.sender = sender;
	}

	public String getSender() {
		return sender;
	}

} 